﻿/// <reference path="vswd-ext_2.2.js" />
function showCustomerConfigWindow() {
	function msgUpdateSuccess() {
		Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
		Ext.Msg.show({
			title: _CustomerConfigResource_Tip,
			msg: _CustomerConfigResource_Success,
			buttons: Ext.Msg.OK,
			animEl: 'elId',
			icon: Ext.MessageBox.INFO
		});
	};
	
	function msgUpdateFailure() {
		Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
		Ext.Msg.show({
			title: _CustomerConfigResource_Tip,
			msg: _CustomerConfigResource_Failure,
			buttons: Ext.Msg.OK,
			animEl: 'elId',
			icon: Ext.MessageBox.WARNING
		});
	}

	var alarmeditor = new Ext.ux.grid.RowEditor({
		saveText: _CustomerConfigResource_Update,
		cancelText: _CustomerConfigResource_Cancel
	});

	var stateeditor = new Ext.ux.grid.RowEditor({
		saveText: _CustomerConfigResource_Update,
		cancelText: _CustomerConfigResource_Cancel
	});

	var typestore = new Ext.data.SimpleStore({
		fields: ['id', 'type'],
		data: [
	   ['1', _AlarmResource_SOSButton_Pressed_Input1_Active],
	   ['2', _AlarmResource_ButtonB_Pressed_Input2_Active],
	   ['3', _AlarmResource_ButtonC_Pressed_Input3_Active],
	   ['4', _AlarmResource_Input4_Active],
	   ['5', _AlarmResource_Input5_Active],
	   ['49', _AlarmResource_SOSButton_Released_Input1_InActive],
	   ['50', _AlarmResource_ButtonB_Released_Input2_InActive],
	   ['51', _AlarmResource_ButtonC_Released_Input3_InActive],
	   ['52', _AlarmResource_Input4_InActive],
	   ['53', _AlarmResource_Input5_InActive]
	   ]
	});

	var alarmTypeCombo = new Ext.form.ComboBox({
		triggerAction: 'all',
		lazyRender: true,
		store: typestore,
		displayField: 'type',
		width: 240,
		mode: 'local',
		valueField: 'type',
		editable: false
	});

	//addalarmdefine
	function createAddAlarmDefineWindow() {
		var form = Ext.form.FormPanel({
			bodyStyle: "padding-top:5px",
			width: 380,
			height: 140,
			defaultType: "textfield",
			items: [
				alarmTypeCombo,
				{
					 name: "password",
					 labelStyle: 'padding-left:5px',
					 fieldLabel: _CustomerConfigResource_Expression,
					 allowBlank: false,
					 blankText: _NewForText_CanNotEmpty,
					 width: 200
				}]
		})
		var alarmwindow = new Ext.Window({
			width: 520,
			height: 420,
			resizable: false,
			constrain:true,
			items: [form]
		});
		alarmwindow.show();
	}

	//sm
	var alarmdefinesm = new Ext.grid.CheckboxSelectionModel({
		dataIndex: "DefineID"
	});

	var statedefinesm = new Ext.grid.CheckboxSelectionModel({
		dataIndex: "DefineID"
	});

	
	//cm
	var alarmdefinecm = new Ext.grid.ColumnModel({
		columns: [
			//new Ext.grid.RowNumberer(),
			{
				header: _CustomerConfigResource_AlarmType,
				dataIndex: 'AlarmType',
				width: 200,
				editor: alarmTypeCombo
			},{
				header: _CustomerConfigResource_Expression,
				dataIndex: 'Expression',
				width: 200,
				editor: new Ext.form.TextField({
					allowBlank: false,
					blankText: _CustomerConfigResource_CanNotEmpty,
					initEvents : function() {
						var keyPress = function(e){
							var blockchars = '.';
							var c = e.getCharCode();
							if(blockchars.indexOf(String.fromCharCode(c)) != -1){
								e.stopEvent();
							}
						};
						this.el.on("keypress", keyPress, this);
					}
				})
			}
		]
	});

	var stateDefinedStore = new Ext.data.SimpleStore({
		fields: ['type', 'data'],
		data: [[_ConfigResource_Output1, 0], 
			   [_ConfigResource_Output2, 1], 
			   [_ConfigResource_Output3, 2], 
			   [_ConfigResource_Output4, 3], 
			   [_ConfigResource_Output5, 4], 
			   [_ConfigResource_Input1, 8],
			   [_ConfigResource_Input2, 9], 
			   [_ConfigResource_Input3, 10], 
			   [_ConfigResource_Input4, 11], 
			   [_ConfigResource_Input5, 12]]
	})

	var statedefinecm = new Ext.grid.ColumnModel({
		columns: [
		//new Ext.grid.RowNumberer(),
			{
				header: _CustomerConfigResource_BitIndex,
				dataIndex: 'BitIndex',
				width: 120,
				editor: new Ext.form.ComboBox({
					editable: false,
					triggerAction: 'all',
					store: stateDefinedStore,
					displayField: 'type',
					width: 240,
					mode: 'local',
					valueField: 'type',
					initEvents : function() {
						var keyPress = function(e){
							var blockchars = '.';
							var c = e.getCharCode();
							if(blockchars.indexOf(String.fromCharCode(c)) != -1){
								e.stopEvent();
							}
						};
						this.el.on("keypress", keyPress, this);
					}
				})
			},
			{
				header: _CustomerConfigResource_Expression,
				dataIndex: 'Expression',
				width: 110,
				editor: new Ext.form.TextField({
					allowBlank: false,
					blankText: _CustomerConfigResource_CanNotEmpty,
					initEvents : function() {
						var keyPress = function(e){
							var blockchars = '.';
							var c = e.getCharCode();
							if(blockchars.indexOf(String.fromCharCode(c)) != -1){
								e.stopEvent();
							}
						};
						this.el.on("keypress", keyPress, this);
					}
				})
			},
			{
				header: _CustomerConfigResource_True_exp,
				dataIndex: 'true_exp',
				width: 110,
				editor: new Ext.form.TextField({
					allowBlank: false,
					blankText: _CustomerConfigResource_CanNotEmpty
				})
			},
			{
				header: _CustomerConfigResource_False_exp,
				dataIndex: 'false_exp',
				width: 110,
				editor: new Ext.form.TextField({
					allowBlank: false,
					blankText: _CustomerConfigResource_CanNotEmpty
				})
			}
		]
	});

	//store
	var alarmdefinestore = new Ext.data.JsonStore({
		url: 'HandlerGetAlarmDefineInfo',
		autoLoad: true,
		root: 'data',
		fields: [
		'DefineID',
		'AlarmType',
		'Expression',
		'ControlType'
		]
	});

	var statedefinestore = new Ext.data.JsonStore({
		url: 'HandlerGetStateDefineInfo',
		root: 'data',
		autoLoad: true,
		fields: [
		'DefineID',
		'BitIndex',
		'Expression',
		'ControlType',
		'true_exp',
		'false_exp']
	});

	//----------------------------------
	// Define layout for gird AlarmDefine tab
	//----------------------------------
	var alarmdefinegrid = new Ext.grid.EditorGridPanel({
		store		 : alarmdefinestore,
		cm			 : alarmdefinecm,
		sm			 : alarmdefinesm,
		loadMask	 : true,
		width		 : 500,
		height		 : 350,
		enableHdMenu : false,
		frame		 : true,
		plugins		 : [alarmeditor],
		clicksToEdit : 2,
		tbar		 : [
			{
				//-----------------------
				// Add Button
				//-----------------------
				text: _CustomerConfigResource_AddNew,
				icon: 'Content/images/add.png',
				handler: function() {
					// Create new record default
					var record = alarmdefinegrid.getStore().recordType;
					var p = new record({
						AlarmType	: _AlarmResource_SOSButton_Pressed_Input1_Active,
						Expression	: '',
						ControlType	: 'ADD'
					});

					// Set focus for last row is added
					alarmeditor.stopEditing();
					alarmdefinestore.insert(alarmdefinestore.getCount(), p);
					alarmdefinegrid.getView().refresh();
					alarmdefinegrid.getSelectionModel().selectRow(alarmdefinestore.getCount() - 1);
					alarmeditor.startEditing(alarmdefinestore.getCount() - 1);
				}
			},{
				//-----------------------
				// Delete Button
				//-----------------------
				ref: '../removeBtn',
				disabled: true,
				text: _CustomerConfigResource_Delete,
				icon: 'Content/images/delete.png',
				handler: function() {
					alarmeditor.stopEditing();

					// Show message box
					Ext.MessageBox.show({
						msg: _CustomerConfigResource_Deleting,
						progressText: _CustomerConfigResource_Deleting,
						width: 300,
						wait: true,
						waitConfig: { interval: 200 }
					});

					// Find row select
					var s = alarmdefinegrid.getSelectionModel().getSelections();
					var splitIds = "";
					for (var j = 0; j < s.length; j++) {
						if (s.length == 1) {
							splitIds = s[j].data.DefineID;
						}
						else {
							if (j < (s.length - 1)) {
								splitIds = s[j].data.DefineID + "," + splitIds;
							}
							if (j == (s.length - 1)) {
								splitIds = splitIds + s[j].data.DefineID;
							}
						}
					}

					// Check
					Ext.Ajax.request({
						url: 'HandlerADUAlarmDefine',
						success: function(result) {
							Ext.MessageBox.hide();
							var flag = eval(result.responseText);
							if (flag != "false") {
								for (var i = 0, r; r = s[i]; i++) {
									alarmdefinestore.remove(r);
									getAlarmDefine();
									Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted)
								}
							}
							else {
								msgUpdateFailure();
							}
						},
						failure: function() {
							Ext.MessageBox.hide();
							msgUpdateFailure();
						},
						params: {
							DefineID: splitIds,
							AlarmType: "",
							Expression: "",
							HandlerType: 'Delete'
						}
					})
				}
			},
			{
				//-----------------------
				// Refresh Button
				//-----------------------
				text: _CustomerConfigResource_Refresh,
				icon: 'Content/images/reload16.gif',
				handler: function() {
					alarmdefinestore.reload()
				}
			}
		]
	});

	//----------------------------------
	// Select change event on each row in grid AlarmDefine
	//----------------------------------
	alarmdefinegrid.getSelectionModel().on('selectionchange', function(sm) {
		alarmdefinegrid.removeBtn.setDisabled(sm.getCount() < 1);
	});

	//----------------------------------
	// Event when update or insert in grid AlarmDefine
	//----------------------------------
	function updateAlarmDefine() {
		var record = alarmdefinegrid.getSelectionModel().getSelections()[0];

		Ext.MessageBox.show({
			msg: _CustomerConfigResource_Saving,
			progressText: _CustomerConfigResource_Saving,
			width: 300,
			wait: true,
			waitConfig: { interval: 200 }
		});

		// Add new record
		if (record.data.ControlType == 'ADD') {
			Ext.Ajax.request({
				url: 'HandlerADUAlarmDefine',
				success: function(result) {
					Ext.MessageBox.hide();
					var flag = eval(result.responseText);
					if (flag != "false") {
						msgUpdateSuccess();
						getAlarmDefine();
						record.data.ControlType = 'normal';
						record.data.DefineID = flag

					}
					else {
						msgUpdateFailure();
					}
				},
				failure: function() {
					Ext.MessageBox.hide();
					msgUpdateFailure();
				},
				params: {
					DefineID: "",
					AlarmType: record.data.AlarmType,
					Expression: record.data.Expression,
					HandlerType: 'Add'
				}
			})

		// Update record
		} else {
			Ext.Ajax.request({
				url: 'HandlerADUAlarmDefine',
				success: function(result) {
					Ext.MessageBox.hide();
					var flag = eval(result.responseText);
					if (flag == true) {
						msgUpdateSuccess();
						getAlarmDefine();
						record.data.ControlType = 'normal';
					}
					else {
						msgUpdateFailure();
					}
				},
				failure: function() {
					Ext.MessageBox.hide();
					msgUpdateFailure();
				},
				params: {
					DefineID: record.data.DefineID,
					AlarmType: record.data.AlarmType,
					Expression: record.data.Expression,
					HandlerType: 'Update'
				}
			})
		}
	}

	alarmdefinestore.on('update', updateAlarmDefine);
	var temprecord;

	//----------------------------------
	// Define layout for gird StateDefine tab
	//----------------------------------
	var statedefinegrid = new Ext.grid.EditorGridPanel({
		store			: statedefinestore,
		cm				: statedefinecm,
		sm				: statedefinesm,
		width			: 500,
		height			: 350,
		loadMask		: true,
		enableHdMenu	: false,
		plugins			: [stateeditor],
		frame			: true,
		clicksToEdit	: 2,
		tbar			: [
		{
			text: _CustomerConfigResource_AddNew,
			icon: 'Content/images/add.png',
			handler: function() {
				var record = statedefinegrid.getStore().recordType;
				var p = new record({
					BitIndex: _ConfigResource_Output1,
					Expression: '',
					ControlType: 'ADD'
				});
				stateeditor.stopEditing();
				statedefinestore.insert(statedefinestore.getCount(), p);
				statedefinegrid.getView().refresh();
				statedefinegrid.getSelectionModel().selectRow(statedefinestore.getCount() - 1);
				stateeditor.startEditing(statedefinestore.getCount() - 1);
			}
		}, {
			ref: '../removeBtn',
			disabled: true,
			text: _CustomerConfigResource_Delete,
			icon: 'Content/images/delete.png',
			handler: function() {
				stateeditor.stopEditing();
				Ext.MessageBox.show({
					msg: _CustomerConfigResource_Deleting,
					progressText: _CustomerConfigResource_Deleting,
					width: 300,
					wait: true,
					waitConfig: { interval: 200 }
				});
				var s = statedefinegrid.getSelectionModel().getSelections();
				var splitIds = "";
				for (var j = 0; j < s.length; j++) {
					if (s.length == 1) {
						splitIds = s[j].data.DefineID;
					}
					else {

						if (j < (s.length - 1)) {
							splitIds = s[j].data.DefineID + "," + splitIds;
						}
						if (j == (s.length - 1)) {
							splitIds = splitIds + s[j].data.DefineID;
						}
					}
				}
				Ext.Ajax.request({
					url: 'HandlerADUStateDefine',
					success: function(result) {
						Ext.MessageBox.hide();
						var flag = eval(result.responseText);
						if (flag != "false") {
							for (var i = 0, r; r = s[i]; i++) {
								statedefinestore.remove(r);
								getUserDefineFieldsNames();
								Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted)
							}

						}
						else {
							msgUpdateFailure();
						}
					},
					failure: function() {
						Ext.MessageBox.hide();
						msgUpdateFailure();
					},
					params: {
						DefineID: splitIds,
						BitIndex: "",
						Expression: "",
						true_exp: "",
						false_exp: "",
						HandlerType: 'Delete'
					}
				})
			}
		}, {
			text: _CustomerConfigResource_Refresh,
			icon: 'Content/images/reload16.gif',
			handler: function() {
				statedefinestore.reload()
			}
		}]
	});

	statedefinegrid.getSelectionModel().on('selectionchange', function(sm) {
		statedefinegrid.removeBtn.setDisabled(sm.getCount() < 1);
	});

	//----------------------------------
	// Event when update or insert in grid AlarmDefine
	//----------------------------------
	function updateStateDefine() {
		var record = statedefinegrid.getSelectionModel().getSelections()[0];
		Ext.MessageBox.show({
			msg: _CustomerConfigResource_Saving,
			progressText: _CustomerConfigResource_Saving,
			width: 300,
			wait: true,
			waitConfig: { interval: 200 }
		});
		//-----------------------
		// Add Data
		//-----------------------
		if (record.data.ControlType == 'ADD') {
			var bitExpression = record.data.BitIndex;
			var bitIndex = 0, count = stateDefinedStore.getCount();
			for (var i = 0; i < count; i++) {
				if (stateDefinedStore.getAt(i).get('type') == bitExpression) {
					bitIndex = stateDefinedStore.getAt(i).get('data');
					break;
				}
			}
			Ext.Ajax.request({
				url: 'HandlerADUStateDefine',
				success: function(result) {
					Ext.MessageBox.hide();
					var flag = eval(result.responseText);
					if (flag != "false") {
						msgUpdateSuccess();
						getUserDefineFieldsNames();
						record.data.DefineID = flag;
						record.data.ControlType = 'normal';
					}
					else {
						Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Added)
					}
				},
				failure: function() {
					Ext.MessageBox.hide();
					Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Added)
				},
				params: {
					DefineID: "",
					BitIndex: bitIndex,
					Expression: record.data.Expression,
					true_exp: record.data.true_exp,
					false_exp: record.data.false_exp,
					HandlerType: 'Add'
				}
			})
		//-----------------------
		// Update Data
		//-----------------------
		} else {
			var bitExpression = record.data.BitIndex;
			var bitIndex=0,count= stateDefinedStore.getCount();
			for (var i = 0; i < count; i++) {
				if (stateDefinedStore.getAt(i).get('type') == bitExpression) {
					bitIndex = stateDefinedStore.getAt(i).get('data');
					break;
				}
			}
			Ext.Ajax.request({
				url: 'HandlerADUStateDefine',
				success: function(result) {
					Ext.MessageBox.hide();
					var flag = eval(result.responseText);
					if (flag == true) {
						msgUpdateSuccess();
						getUserDefineFieldsNames();
						record.data.ControlType = 'normal';
					}
					else {
						msgUpdateFailure();
					}
				},
				failure: function() {
					Ext.MessageBox.hide();
					msgUpdateFailure();
				},
				params: {
					DefineID: record.data.DefineID,
					BitIndex: bitIndex,
					Expression: record.data.Expression,
					true_exp: record.data.true_exp,
					false_exp: record.data.false_exp,
					HandlerType: 'Update'
				}
			})
		}
	}

	statedefinestore.on('update', updateStateDefine);

	//tabelpanel
	var tp = new Ext.TabPanel({
		height: 380,
		width: 500,
		activeTab: 0,
		items: [{

			title: _CustomerConfigResource_AlarmDefine,
			iconCls: 'icon-alarmdefine',
			items: [alarmdefinegrid],
			layout:'fit',
			activeTab: 0
		}, {
			iconCls: 'icon-statedefine',
			title: _CustomerConfigResource_StateDefine,
			layout:'fit',
			items: [statedefinegrid]
		}
	]
	});

	var customerConfigWindow = new Ext.Window({
		title:_TrackerMain_CustomerConfig,
		iconCls:'icon-customerdefine',
		width: 520,
		height: 520,
		resizable: true,
		layout:'fit',
		closeAction: 'close',
		items: [tp],
		minimizable: true,
		constrain:true,
		listeners: {
			'minimize': function() {
				addTaskButtonForWindow(customerConfigWindow);
			}
		}
	});
	
	
	customerConfigWindow.show();
}